<?php

namespace app\api\logic;
use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Cache;
use think\facade\Db;
use DateTime;
use app\order\logic\OrderLogic;
class FeiShuMessageLogic extends BasicLogic
{


    /**
     * @desc   获取app_token
     * @author xx
     * @date 2024-09-24
     */
    public function get_app_access_token(){
           $key        = "app_access_token_feishu";
           $token      = Cache::store('redis')->get($key);
           if(empty($token)){
               $app_id                = Config('Logisticskey.fei_shu.app_id');
               $app_secret            = Config('Logisticskey.fei_shu.app_secret');
               $basic_url             = Config('Logisticskey.fei_shu.basic_url');
               $app_access_token_url  = Config('Logisticskey.fei_shu.app_access_token');
               $url                   = $basic_url.$app_access_token_url;
               $data                  = [
                   'app_id'    => $app_id,
                   'app_secret'=> $app_secret,
               ];
               $response = HttpUtil::postDataCurl($url, $data);
               $token    = $response['app_access_token']??'';
               $expire   = $response['expire']??'';
               Cache::store('redis')->set($key, $token,$expire-3);
           }
           return  $token;
        }


    /**
     * @desc   用户发送文本消息
     * @author luckyXiong
     * @date   2024-09-25
     */
    public function send_message($params=[]){
           $open_id = $params['open_id']??'';
           $message = $params['message']??'';
           if(!$open_id){
               return $this->jsonMessage(201,false,'open_id不能为空',null);
           }
           if(!$message){
               return $this->jsonMessage(201,false,'消息不能为空',null);
           }
           $basic_url             = Config('Logisticskey.fei_shu.basic_url');
           $send_message_url      = Config('Logisticskey.fei_shu.app_send_message');
           $url                   = $basic_url.$send_message_url;
           $token                 = self::get_app_access_token();
           $data                  = [
               'receive_id'=>$open_id,
               'msg_type'  =>'text',
               'content'   =>json_encode([
                   'text'=>$message
               ]),
           ];
           $res                   = HttpUtil::postFeiShu($url,$token,$data);
           if($res['code']==0){
               return $this->jsonMessage(200,true,$res['msg'],null);
           }else{
               return $this->jsonMessage(201,false,$res['msg'],null);
           }
    }


    /**
     * @desc   获取在线表格数据
     * @author luckyXiong
     * @date   2024-10-24
     */
    public function getTablerecords($params=[]){
        $basic_url             = Config('Logisticskey.fei_shu.basic_url');
        $get_table_list        = Config('Logisticskey.fei_shu.get_table_list');
        $table_id              = $params['table_id']??'';
        $table_token           = $params['table_token']??'';
        if(!$table_id)           $this->jsonMessage(201, false, 'table_id不能为空!', null);
        $token                 = self::get_app_access_token();
        $url                   = $basic_url.$get_table_list.$table_token.'/tables/'.$table_id.'/records';
        $res                   = HttpUtil::getFeiShu($url,$token,[]);
        if($res['code']==0){
            $list = $res['data']['items'];
            $arr = [];
            foreach($list as $v){
                    $info = $v['fields'];
                    if(!isset($info['采购批次号/合同编号']) || !$info['采购批次号/合同编号']) continue;
                    $values =  self::change_data($info);
                    if($values){
                        $arr[] = $values;
                    }
            }

            //数据批量存入库
            if($arr){
                Db::name('purchase_inventory')->insertAll($arr);
            }
            return      $this->jsonMessage(200,true,$res['msg'],null);
        }else{
            return      $this->jsonMessage(201,false,$res['msg'],null);
        }
    }




    /**
     * @desc   整理数据格式
     * @author luckyXiong
     * @date   2024-10-25
     */
    private function change_data($info=[]){
        $delivery_status = $info['交货进度'][0]['text']??'';
        $supply_name     = $info['供货商']??'';
        $data =  [
            'delivery_status'     => filterEmoji($delivery_status)=='已延期' ? 2 : 1,
            'spu'                 => $info['产品编号']??'',
            'supply_name'         => trim($supply_name),
            'supply_id'           => self::get_supply_info($supply_name),
            'update_operator'     => $info['修改人']['name']??'',
            'create_operator'     => $info['创建人']['name']??'',
            'arrival_status'      => isset($info['到货状态']) && $info['到货状态'] =='已完成' ? 2 :1,
            'product_name'        => $info['商品名称']??'',
            'remark'              => $info['备注']??'',
            'real_delivery_nums'  => $info['实际交货数量']??'0',
            'actual_delivery_time'=> isset($info['实际交货日期'])&&$info['实际交货日期'] ? date("Y-m-d H:i:s", $info['实际交货日期']/1000) : null,
            'purchase_code'       => $info['采购单号']??'',
            'contract_number'     => $info['采购批次号/合同编号']??'',
            'purchase_time'       => isset($info['采购日期/合同签订日期']) && $info['采购日期/合同签订日期']? date("Y-m-d H:i:s", $info['采购日期/合同签订日期']/1000) : null,
            'dev_delivery_nums'   => $info['预计交货数量']??'0',
            'pre_delivery_time'   => isset($info['预计交货日期']) && $info['预计交货日期']  ? date("Y-m-d H:i:s", $info['预计交货日期']/1000) : null,
        ];

        $res = Db::name('purchase_inventory')->where(['contract_number'=>$data['contract_number'],'spu'=>$data['spu']])->find();
        if($res){
            Db::name('purchase_inventory')->where('id',$res['id'])->update($data);
            return  '';
        }else{
            return  $data;
        }
    }


    /**
     * @desc   获取供货商ID
     * @author luckyXiong
     * @date   2024-10-25
     */
    private function get_supply_info($supply_name){
        $info = Db::name('supply')->where('supply_name',$supply_name)->find();
        return $info['id']??'';
    }



    /**
     * @desc   整理数据格式到货
     * @author luckyXiong
     * @date   2024-10-25
     */
    private function change_data_arrive($info=[]){
        $data = [
            'purchase_code'       => $info['采购单号']??'',
            'contract_number'     => $info['采购批次号/合同编号']??'',
            'spu'                 => $info['产品编号']??'',
            'package_nums'        => $info['箱数/袋数']??'0',
            'arrival_nums'        => $info['到货数量']??'0',
            'track_name'          => $info['物流商']??'',
            'track_number'        => $info['物流单号']??'',
            'create_operator'     => $info['创建人']['name']??'',
            'update_operator'     => $info['修改人']['name']??'',
            'remark'              => $info['备注']??'',
            'create_time'         => date("Y-m-d H:i:s",time()),
            'update_time'         => date("Y-m-d H:i:s",time()),
            'store_time'          => isset($info['入库日期'])&&$info['入库日期'] ? date("Y-m-d H:i:s", $info['入库日期']/1000) : null,
        ];
        $res = Db::name('purchase_arrive_inventory')->where(['contract_number'=>$data['contract_number'],'spu'=>$data['spu'],'store_time'=>$data['store_time']])->find();
        if($res){
            Db::name('purchase_arrive_inventory')->where('id',$res['id'])->update($data);
            return  '';
        }else{
            return  $data;
        }

    }

    /**
     * @desc   整理数据格式
     * @author luckyXiong
     * @date   2024-10-25
     */
    private function change_data_pants($info=[]){
        $supply_name     =   $info['厂家']??'';
        $defective_rate  =   '0';
        if(isset($info['不合格']) && isset($info['抽检数量'])){
            $defective_rate = $info['不合格']/$info['抽检数量'];
            if($defective_rate){
                $defective_rate = round($defective_rate, 4);
            }
        }
        $data =  [
            'spu'                 => $info['品名']??'',
            'supply_name'         => trim($supply_name),
            'supply_id'           => self::get_supply_info($supply_name),
            'create_operator'     => '黄玲',
            'arrival_nums'        => $info['到货数量']??'0',
            'unqualified_nums'    => $info['不合格']??'0',
            'qualified_nums'      => $info['合格']??'0',
            'defective_rate'      => $defective_rate,
            'defective_desc'      => $info['不良描述']??'',
            'remark'              => $info['备注']??'',
            'check_nums'          => $info['抽检数量']??'0',
            'check_time'          => isset($info['日期'])&&$info['日期'] ? date("Y-m-d H:i:s", $info['日期']/1000) : null,
            'create_time'         => date("Y-m-d H:i:s",time()),
        ];

        $res = Db::name('purchase_pants_inventory')->where(['check_time'=>$data['check_time'],'spu'=>$data['spu']])->find();
        if($res){
            Db::name('purchase_pants_inventory')->where('id',$res['id'])->update($data);
            return  '';
        }else{
            return  $data;
        }
    }


    /**
     * @desc   整理数据格式
     * @author luckyXiong
     * @date   2024-12-23
     */
    private function change_spend_info($info=[]){
        return [
            'open_id'     => $info['运营'][0]['id']??'',
            'user_name'   => $info['运营'][0]['name']??'',
            'spend'       => $info['花费']??'0',
            'platform'    => $info['广告平台']??'',
            'month'       => '2024-10',
            'create_time' => date("Y-m-d H:i:s",time()),
        ];
    }


    /**
     * @desc   整理数据格式
     * @author luckyXiong
     * @date   2025-06-20
     */
    public function get_stock_info($info){
        $date    = self::get_new_nums($info);
        $dateKey = key($date);
        $value   = $date[$dateKey];
        $dateKey = self::convertDateFormat($dateKey);
        $spu     = $info['SPU']??'';
        //获取当前记录;
        $supply_id    = Db::name('supply_info')->where('spu',$spu)->value('supply_id');
        $supply_name  = Db::name('supply')->where('id',$supply_id)->value('supply_name');
        $product_info = Db::name('product')->field('id,spu,product_name,product_images')->where('spu',$spu)->find();
        $product_images   = $product_info['product_images']??[];
        $display_images   = $product_images ? current(json_decode($product_images)) : '';
        $sku              = $info['SKU']??'';
        $data             = [];
        if(strpos($sku, '+') !== false){
            $parts   = self::get_sku_infos(['SKU'=>$sku,'num'=>$value],1);
            foreach($parts as $v){
                $temp =  [
                    'spu'         => $info['SPU']??'',
                    'seller_sku'  => $v['SKU']??'',
                    'date_info'   => $dateKey,
                    'supply_id'   => $supply_id,
                    'supply_name' => $supply_name,
                    'product_name'=> $product_info['product_name'],
                    'nums'        => $v['num']??'',
                    'current_nums'=> 0,
                    'image_url'   => $display_images,
                    'create_time' => date("Y-m-d H:i:s",time()),
                ];
                $data[] = $temp;
            }
        }else{
            $temp =  [
                'spu'         => $info['SPU']??'',
                'seller_sku'  => $sku,
                'date_info'   => $dateKey,
                'supply_id'   => $supply_id,
                'supply_name' => $supply_name,
                'product_name'=> $product_info['product_name'],
                'nums'        => $value,
                'current_nums'=> 0,
                'image_url'   => $display_images,
                'create_time' => date("Y-m-d H:i:s",time()),
            ];
            $data[] = $temp;
        }
        Db::name('product_stock_sku')->insertAll($data);
        return  true;
     }


    /**
     * @desc   修改日期格式
     * @author luckyXiong
     * @date   2025-06-21
     */
     private function convertDateFormat($dateStr) {
        // 检查日期字符串格式是否正确
        if (preg_match('/^(\d+)月(\d+)日$/u', $dateStr, $matches)) {
            // 获取月份和日期
            $month = str_pad($matches[1], 2, '0', STR_PAD_LEFT); // 用零填充
            $day = str_pad($matches[2], 2, '0', STR_PAD_LEFT);   // 用零填充
            // 返回转换后的格式
            return  date("Y").'-'.$month . '-' . $day;
        }else{
            // 返回原字符串或错误信息
            return "格式错误";
        }
    }


     private function get_sku_infos($originalArray){
         // Split the SKU into parts
         $skuParts = explode('-', $originalArray['SKU']);
         $colorParts = explode('+', $skuParts[1]);
         // Count occurrences of each color
         $colorCounts = array_count_values($colorParts);
         // Create the new arrays
         $newArray = array();
         foreach ($colorCounts as $color => $count) {
             $newArray[] = array(
                 'num' => $originalArray['num'] * $count,
                 'SKU' => $skuParts[0] . '-' . $color . '-' . $skuParts[2]
             );
         }
         return $newArray;
     }




    /**
     * @desc   获取在线表格数据
     * @author luckyXiong
     * @date   2024-10-24
     */
    public function get_tablerecords_arrive($params=[]){
        $basic_url             = Config('Logisticskey.fei_shu.basic_url');
        $get_table_list        = Config('Logisticskey.fei_shu.get_table_list');
        $table_id              = $params['table_id']??'';
        $table_token           = $params['table_token']??'';
        if(!$table_id)           $this->jsonMessage(201, false, 'table_id不能为空!', null);
        $token                 = self::get_app_access_token();
        $url                   = $basic_url.$get_table_list.$table_token.'/tables/'.$table_id.'/records';
        $res                   = HttpUtil::getFeiShu($url,$token,[]);

        if($res['code']==0){
            $list = $res['data']['items'];
            $arr = [];
            foreach($list as $v){
                $info = $v['fields'];
                if(!isset($info['采购批次号/合同编号']) || !$info['采购批次号/合同编号'])  continue;
                $values =  self::change_data_arrive($info);
                if($values){
                    $arr[] = $values;
                }
            }

            //数据批量存入库
            if($arr){
                Db::name('purchase_arrive_inventory')->insertAll($arr);
            }
            return      $this->jsonMessage(200,true,$res['msg'],null);
        }else{
            return      $this->jsonMessage(201,false,$res['msg'],null);
        }
    }


    /**
     * @desc   获取在线表格数据
     * @author luckyXiong
     * @date   2024-10-24
     */
    public function getTablerecordsPants($params=[]){
        $basic_url             = Config('Logisticskey.fei_shu.basic_url');
        $get_table_list        = Config('Logisticskey.fei_shu.get_table_list');
        $table_id              = $params['table_id']??'';
        $table_token           = $params['table_token']??'';
        if(!$table_id)     $this->jsonMessage(201, false, 'table_id不能为空!', null);
        $token                 = self::get_app_access_token();
        $url                   = $basic_url.$get_table_list.$table_token.'/tables/'.$table_id.'/records';
        $res                   = HttpUtil::getFeiShu($url,$token,[]);
        if($res['code']==0){
            $list = $res['data']['items'];
            $arr = [];
            foreach($list as $v){
                $info   = $v['fields'];
                if(!isset($info['品名']) || !$info['品名'])  continue;
                $values =  self::change_data_pants($info);
                if($values){
                    $arr[] = $values;
                }
            }
            //数据批量存入库
            if($arr){
                Db::name('purchase_pants_inventory')->insertAll($arr);
            }
            return      $this->jsonMessage(200,true,$res['msg'],null);
        }else{
            return      $this->jsonMessage(201,false,$res['msg'],null);
        }
    }


    /**
     * @desc   获取运营广告花费数据
     * @author luckyXiong
     * @date   2024-12-23
     */
    public function getTablerecordsSpend($params=[]){
        $basic_url             = Config('Logisticskey.fei_shu.basic_url');
        $get_table_list        = Config('Logisticskey.fei_shu.get_table_list');
        $table_id              = $params['table_id']??'';
        $table_token           = $params['table_token']??'';
        $token                 = self::get_app_access_token();
        $url                   = $basic_url.$get_table_list.$table_token.'/tables/'.$table_id.'/records';
        $res                   = HttpUtil::getFeiShu($url,$token,[]);
        if($res['code']==0){
            $list = $res['data']['items'];
            $arr = [];
            foreach($list as $v){
                $info   = $v['fields'];
                if(!isset($info['运营'][0]['id']) || empty($info['花费']))  continue;
                $values =  self::change_spend_info($info);
                if($values){
                    $arr[] = $values;
                }
            }
            //数据批量存入库
            if($arr){
                Db::name('advertising_month')->insertAll($arr);
            }
            return      $this->jsonMessage(200,true,$res['msg'],null);
        }else{
            return      $this->jsonMessage(201,false,$res['msg'],null);
        }
    }

    /**
     * @desc   获取员工花名册信息消费方法
     * @author luckyXiong
     * @date   2024-10-29
     */
    public function upEmployeesConsumer($info){
        htmlLog(['params'=>$info],OPERATE_LOG . date('Ym') . '/upEmployeesConsumer/' . date('Ymd') . '.txt');
        $basic_url             = Config('Logisticskey.fei_shu.basic_url');
        $get_table_list        = Config('Logisticskey.fei_shu.get_employees_list');
        $token                 = self::get_app_access_token();
        $open_id               = $info['open_id']??'';
        $admin_id              = $info['id']??'';
        $url                   = $basic_url.$get_table_list.'?user_ids='.$open_id.'&view=full';
        $return                = HttpUtil::getFeiShu($url,$token,[]);
        if(!isset($return['data']['items'][0]['system_fields']) || empty($return['data']['items'][0]['system_fields']))  return [201, false, '暂无数据!',null];
        $info = $return['data']['items'][0]['system_fields'];
        if(isset($info['status']) && $info['status']!=2){
            // 2是在职,其他均为离职
            $update_info = [
                'status'          =>0,
                'employees_status'=>2,
            ];
            if(isset($info['last_day']) && $info['last_day']){
                $update_info['last_time'] = date("Y-m-d H:i:s",strtotime($info['last_day']));
            }
            Db::name('system_admin')->where(['id'=>$admin_id])->update($update_info);
        }
        return true;
    }


    /**
     * @desc   获取飞书员工信息
     * @author luckyXiong
     * @date   2025-04-28
     */
    public function getEmployeesList(){
        $basic_url             = Config('Logisticskey.fei_shu.basic_url');
        $get_table_list        = Config('Logisticskey.fei_shu.get_employees_list');
        $token                 = self::get_app_access_token();
        $url                   = $basic_url.$get_table_list.'?page_size=100';
        $return                = HttpUtil::getFeiShu($url,$token,[]);
        $info                  = $return['data']['items']??[];
        $arr                   = [];
        foreach($info as $k=>$v){
            $temp['username'] = $v['system_fields']['name']??'';
            $temp['user_id']  = $v['user_id']??'';
            $arr[] = $temp;
        }

        foreach($arr as  $v){
            $exist_info = Db::name('system_admin')->where(['username'=>$v['username']])->find();
            if($exist_info){
                Db::name('system_admin')->where(['id'=>$exist_info['id']])->update([
                    'open_id'=>trim($v['user_id']),
                ]);
            }
        }
    }



    /**
     * @desc   缺货明细列表数据
     * @author luckyXiong
     * @date   2025-06-20
     */
    public function stock_detail($params){

        $table_id              = $params['table_id']??'';
        $table_token           = $params['table_token']??'';
        $token                 = self::get_app_access_token();
        $next_page_token       = '';
        //update 2025-06-14  qu_product_stock_sku，获取最新的;
        Db::execute('TRUNCATE TABLE qu_product_stock_sku');
        do{
            $return_list     = self::gets_message($table_id, $table_token,$token,$next_page_token);
            if($return_list['code']!='0'){
                 self::send_check_info();
                 break;
            }
            $messages_info   = $return_list['data']['items']??'';
            $next_page_token = $return_list['data']['page_token']??'';
            self::insert_message($messages_info);
            if(empty($next_page_token)) {
                break;
            }
           }while(true);
      }


    /**
     * @desc   通知消息
     * @author luckyXiong
     * @date   2025-06-25
     */
    private function send_check_info(){
        $open_id = Db::name('system_admin')->field('open_id')->where(['id'=>2])->value('open_id');
        $datamsg = [
            'message' => '缺货建议数据没有获取到',
            'open_id' => $open_id,
        ];
        (new FeiShuMessageLogic())->send_message($datamsg);
    }


    /**
     * @desc   写入消息数据
     * @author luckyXiong
     * @date   2025-06-25
     */
     private function insert_message($list){
             if($list){
                 if(isset($list[0])) unset($list[0]);
                 $list = array_values($list);
                 foreach($list as $v){
                     $info  = $v['fields'];
                     // 队列处理
                     MqTaskPushLogic::mq_task_push(
                         '',
                         MqQueueName::QUEUE_ORDER_STOCK_SKU_QUEUE,
                         $info,
                         false
                     );
                 }
             }
     }


    /**
     * @desc   获取数据
     * @author luckyXiong
     * @date   2025-06-25
     */
    private function gets_message($table_id, $table_token,$token,$page_token){
        $basic_url             = Config('Logisticskey.fei_shu.basic_url');
        $get_table_list        = Config('Logisticskey.fei_shu.get_table_list');
        if($page_token){
            $url             = $basic_url.$get_table_list.$table_token.'/tables/'.$table_id.'/records'.'?page_size=' . '500'. '&page_token=' . $page_token;
        }else{
            $url             = $basic_url.$get_table_list.$table_token.'/tables/'.$table_id.'/records';
        }
        return HttpUtil::getFeiShu($url,$token,[]);
    }






    /**
     * @desc   获取最新日期
     * @author luckyXiong
     * @date   2025-06-20
     */
    private function get_new_nums($data){
        $dates = [];
        foreach ($data as $key => $value) {
            if (preg_match('/^\d+月\d+日$/', $key)) { // 匹配 "X月X日" 格式
                $dates[$key] = $value;
            }
        }
        // 2. 如果没有日期数据，返回空
        if (empty($dates)) {
            echo "没有找到日期数据";
            exit;
        }

        // 3. 将日期转换为可比较的时间戳
        $dateTimestamps = [];
        foreach ($dates as $dateStr => $value) {
            // 替换中文月份和日，并解析为 DateTime 对象
            $dateStr = str_replace(['月', '日'], ['-', ''], $dateStr);
            $dateTime = DateTime::createFromFormat('m-d', $dateStr);
            if ($dateTime) {
                $dateTimestamps[$dateTime->getTimestamp()] = [
                    'date' => $dateStr,
                    'value' => $value
                ];
            }
        }
        // 4. 找出最大的时间戳（即最新日期）
        if (!empty($dateTimestamps)) {
            $maxTimestamp = max(array_keys($dateTimestamps));
            $latestDate = $dateTimestamps[$maxTimestamp]['date'];
            $latestValue = $dateTimestamps[$maxTimestamp]['value'];

            // 转换回 "X月X日" 格式
            $latestDateFormatted = str_replace('-', '月', $latestDate) . '日';

            // 输出结果
            $result = [$latestDateFormatted => $latestValue];
            return  $result;
        } else {
            echo "无法解析日期";
        }
    }










  }